﻿using Core.Authorization;
using Core.Extensions;
using Core.Identity.Tokens;
using Core.Identity.Tokens.Features.Generate;
using Core.Identity.Tokens.Features.Refresh;
using Core.Identity.Tokens.Models;
using Core.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;

namespace Infrastructure.Identity.Tokens.Endpoints;

public static class TokenEndpoints
{
    /// <summary>
    /// 注册 Token 相关 Minimal API
    /// </summary>
    public static IEndpointRouteBuilder MapTokenEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/token")
                       .WithTags("Token")
                       .AllowAnonymous(); // 允许匿名访问

        // POST /api/token/generate
        group.MapPost("/generate", GenerateTokenAsync)
             .WithDescription("生成令牌")
             .WithMetadata(new EndpointNameMetadata(nameof(GenerateTokenAsync)));

        // POST /api/token/refresh
        group.MapPost("/refresh", RefreshTokenAsync)
             .WithDescription("刷新令牌")
             .WithMetadata(new EndpointNameMetadata(nameof(RefreshTokenAsync)));

        return app;
    }

    /// <summary>
    /// 生成令牌
    /// </summary>
    private static async Task<Result<TokenResponse>> GenerateTokenAsync(
        [FromHeader(Name = TenantConstants.Identifier)] string tenant,
        [FromBody] TokenGenerationCommand request,
        HttpContext httpContext,
        [FromServices] ITokenService tokenService)
    {
        string ip = httpContext.GetIpAddress();
        return await tokenService.GenerateTokenAsync(request, ip);
    }

    /// <summary>
    /// 刷新令牌
    /// </summary>
    private static async Task<Result<TokenResponse>> RefreshTokenAsync(
        [FromHeader(Name = TenantConstants.Identifier)] string tenant,
        [FromBody] RefreshTokenCommand request,
         HttpContext httpContext,
        [FromServices] ITokenService tokenService)
    {
        string ip = httpContext.GetIpAddress();
        return await tokenService.RefreshTokenAsync(request, ip);
    }
}
